import React, {useState,useEffect} from 'react'
import { View, Text, StyleSheet, Image, SafeAreaView, Button} from 'react-native'
import {Toast} from '@ant-design/react-native'
import {
  CodeField,
  Cursor,
  useBlurOnFulfill,
  useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import { TouchableOpacity } from 'react-native-gesture-handler'
import { Header } from '../../components'
import { pxToPt } from '../../utils/pxToPt'
import { GET, POST } from '../../utils';
import { VERIFYURL } from '../../service';


export default class Index extends React.Component {
  state = {
    resentBtn: true,
    value: '',
    waitTime: 60,
    userInfo:{}
  }
  resent = () => { 
    if(!this.state.resentBtn){
        return
    }
    this.setState({resentBtn: false})
    this.timer = setInterval(()=> {
       this.setState((prev)=>({waitTime: prev.waitTime-1}))
       if(this.state.waitTime===0){
         clearInterval(this.timer)
         this.setState({resentBtn: true, waitTime: 60})
       }
    }, 1000)
    GET(`${VERIFYURL + this.props.route.params.mobile}`).then(res=> {
      if(res.message==='ok') {
        this.setState({userInfo: {...this.props.route.params, ...{verifyCode :res.verifyCode}}})
      }else{
        Toast.info(res.message)
      }
    })
      Toast.info('send success !!!', 1);
  }

  commit = () => {
    const {navigation} = this.props
   if(this.state.value.length===6) {
    POST('/users/', { data: this.state.userInfo}).then(res=> {
      alert(JSON.stringify(res))
      if(res.id) {
        Toast.success('注册成功')
        navigation.navigate('Login')
      }else(
        Toast.info('请求失败请重试')
      )
    })
   }
  }
  UNSAFE_componentWillMount() {
    if(this.props.route){
      this.resent()
    }
  }
  componentWillUnmount() {
    clearInterval(this.timer)
  }

  render() {
    const {navigation} = this.props
    const {resentBtn, value, waitTime, userInfo} = this.state
    return  (
      <View style={styles.wrapper}>
        <View style={styles.container} >  
          <View style={styles.header}>
            <Header
              LeftIcon='ZUO'
              leftPress={()=> {navigation.goBack()}}
            />
          </View>
          <View style={styles.form}>
            <Image style={styles.bg} source={require('../../../assets/bg/verify_bg.png')} />
            <Text style={styles.title}>Verification code</Text>
            <Text style={styles.tips}>Please type the verification code sent to your phone {userInfo['mobile']} </Text>
            <CodeField
              value={value}
              onChangeText={(value)=>{this.setState({value})}}
              cellCount={6}
              rootStyle={styles.codeFieldRoot}
              keyboardType="number-pad"
              textContentType="oneTimeCode"
              renderCell={({index, symbol, isFocused}) => (
                <Text
                  key={index}
                  style={[styles.cell, isFocused && styles.focusCell]}
                 >
                  {symbol || (isFocused ? <Cursor /> : null)}
                </Text>
              )}
              />
              <TouchableOpacity onPress={this.commit.bind(this)}>
                <View style={styles.btnStyle}>
                  <Button color='#15172B'  title='Submit' />
                </View>
            </TouchableOpacity>
            {
              resentBtn?
               (<Text onPress={this.resent.bind(this)} style={styles.resent}>Resent</Text>):(
                <Text style={styles.resent}>{`after ${waitTime}'s resent` }</Text>
               )
            }
          </View>
        </View>
        <View style={styles.footer}>
          <Text style={styles.link}>Don’t have an account? <Text  onPress={ ()=>navigation.navigate('Login')} style={styles.jump}>SIGN UP</Text></Text>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  wrapper: {
    flex: 1
  },
  container: {
    flex: 1,
    backgroundColor: '#212529',
    paddingLeft: pxToPt(25),
    paddingRight: pxToPt(25),
  },
  header: {
    marginTop: pxToPt(64)
  },
  
  form: {
    marginTop: pxToPt(40),
  },

  btnStyle: {
    width: pxToPt(230),
    height: pxToPt(52),
    borderRadius: pxToPt(25),
    backgroundColor: '#6AC4AC',
    marginTop: pxToPt(30),
    alignSelf: 'center',
    alignItems: 'center',
    justifyContent: 'center'
  },
  footer: {
    height: pxToPt(60),
    width: '100%',
    position: 'absolute',
    left: 0,
    bottom: 0,
    borderTopWidth: pxToPt(0.2),
    borderTopColor: 'rgba(255, 255, 255, 0.1)',
  },
  link: {
    textAlign: 'center',
    lineHeight: pxToPt(60),
    fontSize: pxToPt(13),
    color: '#8A9EAD'
  },
  jump: {
    color: '#45E9BD'
  },
  title: {textAlign: 'center', fontSize: 30},
  codeFieldRoot: {marginTop: 40, },
  cell: {
    width: 40,
    height: 40,
    lineHeight: 38,
    fontSize: 24,
    borderWidth: 2,
    borderColor: '#00000030',
    textAlign: 'center',
    color: '#FFF'
  },
  focusCell: {
    borderColor: '#000',
  },
  bg: {
    width: pxToPt(158.15),
    alignSelf: 'center'
  },
  title: {
    fontSize: pxToPt(23),
    color: '#FFF',
    fontWeight: 'bold',
    alignSelf: 'center',
    marginTop: pxToPt(30)
  },
  tips: {
    width: pxToPt(270),
    fontSize: pxToPt(13),
    textAlign: 'center',
    alignSelf: 'center',
    color: '#FFF',
    marginTop: pxToPt(20)
  },
  resent: {
    marginTop: pxToPt(20),
    alignSelf: 'center',
    color: '#FFF',
    fontSize: pxToPt(13)
  }
})
